<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="项目阶段" prop="projectPhase">
        <el-select v-model="queryParams.projectPhase" placeholder="请选择阶段" clearable>
          <el-option label="售前" value="售前" />
          <el-option label="方案" value="方案" />
          <el-option label="报价" value="报价" />
          <el-option label="停止" value="停止" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格标题栏 -->
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h3 style="margin: 0; font-size: 16px; font-weight: 600; color: #303133;">售前项目管理</h3>
      <el-button type="primary" icon="Plus" @click="handleAdd">新增售前项目</el-button>
    </div>

    <!-- 主表 -->
    <el-table
      ref="preSalesTable"
      v-loading="loading"
      :data="preSalesProjectList"
      row-key="id"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      :cell-style="{ padding: '8px 0' }">

      <!-- 所有需要展示的字段（除 id） -->
      <el-table-column prop="customerName" label="客户名称" align="left" show-overflow-tooltip width="200" />
      <el-table-column prop="projectName" label="项目名称" align="left" show-overflow-tooltip width="250" />
      <el-table-column prop="amount" label="阶段金额" align="center" width="120" />
      <el-table-column prop="projectPhase" label="项目阶段" align="center" width="120">
        <template v-slot="scope">
          <el-tag :type="getPhaseTagType(scope.row.projectPhase)" size="small">
            {{ scope.row.projectPhase }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="left" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="160">
        <template v-slot="{ row }">
          <div style="display: flex; justify-content: center; gap: 8px;">
            <el-button size="small" type="primary" icon="Edit" @click="handleUpdate(row)">修改</el-button>
            <el-button size="small" type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total>0"
      :total="total"
      :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="getList"
      @size-change="handleSizeChange">
    </el-pagination>

    <!-- 添加 / 修改对话框（包含 remark 和 amount） -->
    <el-dialog :title="title" :visible.sync="open" width="640px" append-to-body>
      <el-form ref="preSalesRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" maxlength="200"/>
        </el-form-item>

        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" maxlength="200"/>
        </el-form-item>

        <el-form-item label="项目阶段" prop="projectPhase">
          <el-select v-model="form.projectPhase" placeholder="请选择项目阶段">
            <el-option label="售前" value="售前"/>
            <el-option label="方案" value="方案"/>
            <el-option label="报价" value="报价"/>
            <el-option label="停止" value="停止"/>
          </el-select>
        </el-form-item>

        <el-form-item label="阶段金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" rows="3" maxlength="500"/>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPreSalesProject,
  getPreSalesProject,
  addPreSalesProject,
  updatePreSalesProject,
  delPreSalesProject
} from "@/api/preSalesProject/preSalesProject";

export default {
  name: "PreSalesProjectIndex",
  data() {
    return {
      preSalesProjectList: [],
      open: false,
      loading: false,
      showSearch: true,
      total: 0,
      title: "",
      form: {
        id: null,
        customerName: "",
        projectName: "",
        projectPhase: "",
        remark: "",
        amount: ""
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: "",
        projectName: "",
        projectPhase: ""
      },
      rules: {
        customerName: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
        projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        projectPhase: [{ required: true, message: "项目阶段不能为空", trigger: "change" }],
        amount: [{ required: true, message: "阶段金额不能为空", trigger: "blur" }]
      }
    };
  },
  created() { this.getList(); },
  methods: {
    getList() {
      this.loading = true;
      listPreSalesProject(this.queryParams).then(res => {
        if (res && res.data) {
          // 直接使用后端返回的 rows（保持字段一致）
          this.preSalesProjectList = res.data.rows || [];
          this.total = res.data.total || 0;
        }
      }).catch(err => {
        console.error("获取售前项目列表失败", err);
      }).finally(() => this.loading = false);
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList(); },
    resetQuery() {
      // resetFields 会清空表单内 model 的值，但也要确保 queryParams 恢复默认
      if (this.$refs.queryRef) this.$refs.queryRef.resetFields();
      this.queryParams = { pageNum: 1, pageSize: this.queryParams.pageSize || 10, customerName: "", projectName: "", projectPhase: "" };
      this.getList();
    },
    handleSizeChange(size) { this.queryParams.pageSize = size; this.getList(); },
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.title = "添加售前项目";
    },
    handleUpdate(row) {
      if (!row || !row.id) return this.$message.error("记录不存在");
      
      // 先重置表单
      this.resetForm();
      
      getPreSalesProject(row.id).then(res => {
        console.log("获取售前项目详情响应:", res); // 调试信息
        const data = res && res.data ? res.data : {};
        console.log("售前项目数据:", data); // 调试信息
        
        // 使用 $nextTick 确保 DOM 更新后再填充数据
        this.$nextTick(() => {
          // 填充表单（确保字段存在）
          this.form = {
            id: data.id || null,
            customerName: data.customerName || "",
            projectName: data.projectName || "",
            projectPhase: data.projectPhase || "",
            remark: data.remark || "",
            amount: data.amount || ""
          };
          console.log("填充后的表单数据:", this.form); // 调试信息
        });
        
        this.open = true;
        this.title = "修改售前项目";
      }).catch(err => {
        this.$message.error("获取详情失败");
        console.error(err);
      });
    },
    submitForm() {
      this.$refs.preSalesRef.validate(valid => {
        if (!valid) return;
        const payload = { ...this.form };
        const req = payload.id ? updatePreSalesProject(payload) : addPreSalesProject(payload);
        this.loading = true;
        req.then(() => {
          this.$message.success(payload.id ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        }).catch(err => {
          this.$message.error((err && err.message) ? err.message : "操作失败");
          console.error(err);
        }).finally(() => {
          this.loading = false;
        });
      });
    },
    cancel() {
      this.open = false;
      this.resetForm();
    },
    resetForm() {
      this.form = { id: null, customerName: "", projectName: "", projectPhase: "", remark: "", amount: "" };
      if (this.$refs.preSalesRef) this.$refs.preSalesRef.resetFields();
    },
    handleDelete(row) {
      if (!row || !row.id) return this.$message.error("请选择要删除的数据");
      this.$confirm(`是否确认删除该售前项目？`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          this.loading = true;
          delPreSalesProject(row.id).then(() => {
            this.$message.success("删除成功");
            this.getList();
          }).catch(err => {
            this.$message.error("删除失败");
            console.error(err);
          }).finally(() => { this.loading = false; });
        }).catch(() => {});
    },
    getPhaseTagType(phase) {
      const map = { '售前': 'warning', '方案': 'primary', '报价': 'success', '停止': 'danger' };
      return map[phase] || 'info';
    }
  }
};
</script>

<style scoped>
.app-container { padding: 16px; }
</style>
